package com.baseproject.helper;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.view.View;

import com.baseproject.R;
import com.baseproject.util.LogUtils;
import com.baseproject.widget.AlertDialog;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action0;
import rx.functions.Action1;

import static com.baseproject.helper.ConstRequestCode.REQUEST_CODE_PERMISSION_SETTING;

/**
 * android6.0版本开始的动态权限验证helper类
 * 权限申请，首先要在manifest中注册，其次再按需动态申请
 */

public class PermissionHelper {

    private static PermissionHelper instance;
    private AlertDialog alertDialogPermission;

    private PermissionHelper() {

    }

    public static PermissionHelper getInstance() {
        if (null == instance) {
            synchronized (PermissionHelper.class) {
                if (null == instance) {
                    instance = new PermissionHelper();
                }
            }
        }
        return instance;
    }

    /**
     * 调用方google规定的一个权限组内只需要申请一个即可
     */
    public void checkPermission(Activity activity, IPermissionListener iPermissionListener, String... permissions) {
        if (permissions.length == 0) {
            return;
        }
        RxPermissions rxPermissions = new RxPermissions(activity);
        List<String> permissionsDenyWithoutNeverAskAgain = new ArrayList<>();
        List<String> permissionsDenyWithNeverAskAgain = new ArrayList<>();
        rxPermissions.requestEach(permissions)
                .doOnTerminate(new Action0() {
                    @Override
                    public void call() {
                        LogUtils.d("doOnTerminate");
                        if (permissionsDenyWithoutNeverAskAgain.size() > 0 || permissionsDenyWithNeverAskAgain.size() > 0) {//确实有仍然需要申请权限的项
                            handlePermissionRequestResult(activity, iPermissionListener, permissionsDenyWithoutNeverAskAgain, permissionsDenyWithNeverAskAgain);
                        } else {
                            hidePermissionDialog();
                            iPermissionListener.allGranted();
                        }
                    }
                })
                .subscribe(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {// will emit permission.length Permission objects after slected all over
                        if (permission.granted) {// permission.name is granted !
                            LogUtils.d("permisson granted! name = " + permission.name);
                            iPermissionListener.granted(permission);
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // Denied permission without never ask again
                            LogUtils.d("permisson denied! name = " + permission.name);
                            permissionsDenyWithoutNeverAskAgain.add(permission.name);
                        } else {
                            // Denied permission with never ask again // Need to go to the settings
                            LogUtils.d("permisson denied and never ask again! name = " + permission.name);
                            permissionsDenyWithNeverAskAgain.add(permission.name);
                        }
                    }
                });
    }

    private void handlePermissionRequestResult(Activity activity, IPermissionListener iPermissionListener,
                                               List<String> permissionsDenyWithoutNeverAskAgain, List<String> permissionsDenyWithNeverAskAgain) {
        String topic = buildPermissionTopic(permissionsDenyWithoutNeverAskAgain, permissionsDenyWithNeverAskAgain);
        if (permissionsDenyWithNeverAskAgain.size() > 0) {//已经有勾选不在询问的权限，只能弹出设置页面请用户设置权限
            List<String> allPermissions = new ArrayList<>(permissionsDenyWithNeverAskAgain);
            allPermissions.addAll(permissionsDenyWithoutNeverAskAgain);
            showPermissionDialog(false, iPermissionListener, activity, topic,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.fromParts("package", activity.getPackageName(), null));
                            activity.startActivityForResult(intent, REQUEST_CODE_PERMISSION_SETTING);
                        }
                    }, (String[]) allPermissions.toArray(new String[]{}));
        } else {//不存在不再询问的勾选，只需要再次申请权限就行
            showPermissionDialog(false, iPermissionListener, activity, topic,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialogPermission.dismiss();
                            checkPermission(activity, iPermissionListener, (String[]) permissionsDenyWithoutNeverAskAgain.toArray(new String[]{}));
                        }
                    });
        }
    }


    private String buildPermissionTopic(List<String> permissionsDenyWithoutNeverAskAgain, List<String> permissionsDenyWithNeverAskAgain) {
        if (permissionsDenyWithoutNeverAskAgain.size() == 0 && permissionsDenyWithNeverAskAgain.size() == 0) {
            return null;
        }
        StringBuilder topic = new StringBuilder();
        for (String permission : permissionsDenyWithoutNeverAskAgain) {
            topic.append(convertPermissonToHint(permission) + ",");
        }
        for (String permission : permissionsDenyWithNeverAskAgain) {
            topic.append(convertPermissonToHint(permission) + ",");
        }
        return topic.substring(0, topic.length() - 1);
    }

    private String convertPermissonToHint(String permission) {
        switch (permission) {
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                return "存储";
            case Manifest.permission.CAMERA:
                return "摄像头";
            default:
                throw new RuntimeException("permission type error!");
        }
    }

    private void hidePermissionDialog() {
        if (alertDialogPermission != null) {
            alertDialogPermission.dismiss();
            alertDialogPermission = null;
        }
    }

    public void dismissAndReCheck(Activity activity, IPermissionListener iPermissionListener, String... permissions) {
        hidePermissionDialog();
        checkPermission(activity, iPermissionListener, permissions);
    }

    protected void showPermissionDialog(boolean isPermission, IPermissionListener iPermissionListener,
                                        Activity activity, String topic, View.OnClickListener onClickListener, String... permissions) {
        if (isPermission) {
            hidePermissionDialog();
            return;
        }
        if (alertDialogPermission == null) {
            alertDialogPermission = new AlertDialog(activity);
            alertDialogPermission._setCanceledOnTouchOutside(false)
                    ._setCancelable(false)
                    ._setDividerColor(R.color.line_driver)
                    ._setTitle("权限设置")
                    .setTitleTextSize(R.dimen.size_32)
                    .setTitleTextColor(R.color._30)
                    .setContentTextSize(R.dimen.size_28)
                    .setPositiveButton("确定", R.color._white, R.color._6FB0FF)
                    .build();
        }

        alertDialogPermission.setContent("\n" + topic + "权限是软件提供优质服务的基础权限，不会涉及访问个人隐私及信息安全，为保证使用体验，请允许访问。\n")
                ._setPositionButtonOnClickListener(onClickListener)
                ._show()
                .setPercentWith(0.85f);
    }
}
